package com.breakfast.fun.ui.home.gallery;

import android.content.Intent;
import android.graphics.Bitmap;
import android.support.v4.view.CustomViewPager;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.breakfast.fun.R;
import com.breakfast.fun.adapter.home.GalleryAdapter;
import com.breakfast.fun.base.BaseActivity;
import com.breakfast.fun.common.CommonCart;
import com.breakfast.fun.dao.DaoMaster;
import com.breakfast.fun.dao.ProductCart;
import com.breakfast.fun.dao.ProductCartDao;
import com.breakfast.fun.data.entity.home.Products;
import com.breakfast.fun.event.CartEvent;
import com.breakfast.fun.ui.home.HomeFragment;
import com.breakfast.fun.ui.home.product.NormalProductActivity;
import com.breakfast.fun.ui.user.cart.UserCartActivity;
import com.breakfast.fun.util.BlurUtil;
import com.breakfast.fun.util.L;
import com.breakfast.fun.util.T;
import com.breakfast.fun.view.widget.ZoomCardPageTransformer;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.greenrobot.greendao.query.Query;
import org.greenrobot.greendao.query.QueryBuilder;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;


public class GalleryProductActivity extends BaseActivity<GalleryProductPresenter, GalleryProductModel> implements GalleryProductContract.View {

    @Bind(R.id.iv_gallery_product_close)
    ImageView ivGalleryProductClose;
    @Bind(R.id.cvp_gallery_product)
    CustomViewPager cvpGalleryProduct;
    @Bind(R.id.tv_gallery_product_comment)
    TextView tvGalleryProductComment;
    @Bind(R.id.tv_gallery_product_del)
    TextView tvGalleryProductDel;
    @Bind(R.id.tv_gallery_product_num)
    TextView tvGalleryProductNum;
    @Bind(R.id.tv_gallery_product_add)
    TextView tvGalleryProductAdd;
    @Bind(R.id.tv_gallery_product_buy)
    TextView tvGalleryProductBuy;
    @Bind(R.id.rl_gallery_product_des)
    RelativeLayout rlGalleryProductDes;
    @Bind(R.id.ll_gallery_product)
    LinearLayout llGalleryProduct;

    //    private Products products;                                      //从首页画廊点击进入的products
    private List<Products> mProductsList = new ArrayList<>();       //NormalProductActivity页面的所有products
    private Products curProducts;                                   //从NormalProductActivity进入的被选中products
    private List<Products> list = new ArrayList<Products>();
    private Products product;
    private String closeTime;
    private boolean isCheckDayClose;
    private Boolean isFromGallery = false;
    private int position = 0;
    private ProductCartDao mProductCartDao;
    private QueryBuilder qb;

    private CommonCart mCommonCart = new CommonCart();

    private List<ProductCart> productCarts;

    private String imageIndexStr = "";

    @Override
    public int getLayoutId() {
        return R.layout.activity_gallery_product;
    }

    @Override
    public void initView() {

        EventBus.getDefault().register(this);

        getWindow().setLayout(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT);

        mProductCartDao = DaoMaster.newDevSession(context, "zaofan.db").getProductCartDao();

        curProducts = (Products) getIntent().getSerializableExtra("curProducts");
        mProductsList = (List<Products>) getIntent().getSerializableExtra("productLists");
        closeTime = getIntent().getStringExtra("closeTime");
        isCheckDayClose = getIntent().getBooleanExtra("isCheckDayClose", false);
        isFromGallery = getIntent().getBooleanExtra("isFromGallery", false);

        if (isFromGallery) {
            imageIndexStr = "http://www.52letsgo.cn";
        }

        //初始化购物车event
        mCommonCart.init(context);
        productCarts = mCommonCart.productCartDao.loadAll();
        for (int i = 0; i < productCarts.size(); i++) {
            mCommonCart.totalPrice += productCarts.get(i).getTotalPrice();
            mCommonCart.totalNum += productCarts.get(i).getNum();
        }
        mCommonCart.event.setTotalPrice(mCommonCart.totalPrice);
        mCommonCart.event.setTotalNum(mCommonCart.totalNum);
        EventBus.getDefault().post(mCommonCart.event);


        list.clear();
        list.addAll(mProductsList);
        product = curProducts;

        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getProduct().getId() == product.getProduct().getId()) {
                position = i;
                Glide.with(context)
                        .load(imageIndexStr + list.get(position).getProduct().getBigImage())
                        .asBitmap()
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                BlurUtil.blur(getBaseContext(), resource, llGalleryProduct);
                            }
                        });
                List<ProductCart> productCartList = getProductList(list.get(position).getProduct().getCategoryId(),
                        list.get(position).getProduct().getId(), list.get(position).getDate());
                if (productCartList != null && productCartList.size() > 0) {
                    tvGalleryProductNum.setText(productCartList.get(0).getNum() + "");
                }
                tvGalleryProductComment.setOnClickListener(v -> {
                    Intent intent = new Intent(context, ProductCommentActivity.class);
                    intent.putExtra("productId", list.get(position).getProduct().getId() + "");
                    startActivity(intent);
                    GalleryProductActivity.this.finish();
                });

            }
        }
        GalleryAdapter adapter = new GalleryAdapter(context, list, isFromGallery);
        cvpGalleryProduct.setAdapter(adapter);
        cvpGalleryProduct.setPageMargin(10);
        cvpGalleryProduct.setPageTransformer(true, new ZoomCardPageTransformer(cvpGalleryProduct, true));
        cvpGalleryProduct.setOffscreenPageLimit(5);
        cvpGalleryProduct.setCurrentItem(position);


        cvpGalleryProduct.addOnPageChangeListener(new CustomViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                Glide.with(context)
                        .load(imageIndexStr + list.get(position).getProduct().getBigImage())
                        .asBitmap()
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                BlurUtil.blur(getBaseContext(), resource, llGalleryProduct);
                            }
                        });

                List<ProductCart> productCartList = getProductList(list.get(position).getProduct().getCategoryId(),
                        list.get(position).getProduct().getId(), list.get(position).getDate());
                if (productCartList != null && productCartList.size() > 0) {
                    tvGalleryProductNum.setText(productCartList.get(0).getNum() + "");
                } else {
                    tvGalleryProductNum.setText("0");
                }
                tvGalleryProductComment.setOnClickListener(v -> {
                    Intent intent = new Intent(context, ProductCommentActivity.class);
                    intent.putExtra("productId", list.get(position).getProduct().getId() + "");
                    startActivity(intent);
                    GalleryProductActivity.this.finish();
                });

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        ivGalleryProductClose.setOnClickListener(v -> {
            finish();
        });

        llGalleryProduct.setOnClickListener(v -> {
            finish();
        });

//        if (!isFromGallery) {
        tvGalleryProductComment.setOnClickListener(v -> {
            Intent intent = new Intent(context, ProductCommentActivity.class);
            intent.putExtra("productId", product.getProduct().getId() + "");
            startActivity(intent);
            GalleryProductActivity.this.finish();
        });
        tvGalleryProductAdd.setOnClickListener(v -> {
            addProduct(mProductsList.get(cvpGalleryProduct.getCurrentItem()));
        });

        tvGalleryProductDel.setOnClickListener(v -> {
            delProduct(mProductsList.get(cvpGalleryProduct.getCurrentItem()));
        });
//
//        } else {
//
//            tvGalleryProductAdd.setOnClickListener(v -> {
//                addProduct(HomeFragment.productsList.get(cvpGalleryProduct.getCurrentItem()));
//            });
//
//            tvGalleryProductDel.setOnClickListener(v -> {
//                delProduct(HomeFragment.productsList.get(cvpGalleryProduct.getCurrentItem()));
//            });
//        }
        tvGalleryProductBuy.setOnClickListener(v -> {
            if (tvGalleryProductNum.getText().equals("0")) {
                T.show("请先添加商品数量");
                return;
            }
            Intent intent = new Intent(this, UserCartActivity.class);
            startActivity(intent);
            GalleryProductActivity.this.finish();
        });

    }

    private void delProduct(Products products) {
        if (tvGalleryProductNum.getText().equals("0")) {
            return;
        }
        String date = "";
        if (isFromGallery) {
            date = HomeFragment.chooseDate;
        } else {
            date = NormalProductActivity.chooseDate;
        }
        List<ProductCart> productCartList = getProductList(products.getProduct().getCategoryId(), products.getProduct().getId(), date);

        productCartList.get(0).setNum(productCartList.get(0).getNum() - 1);
        productCartList.get(0).setTotalPrice(productCartList.get(0).getPrice() * productCartList.get(0).getNum());
        mProductCartDao.update(productCartList.get(0));

        if (productCartList.get(0).getNum() == 0) {
            mProductCartDao.delete(productCartList.get(0));
        }

        mCommonCart.totalNum -= 1;
        mCommonCart.totalPrice -= products.getProduct().getPrice();
        mCommonCart.event.setTotalNum(mCommonCart.totalNum);
        mCommonCart.event.setTotalPrice(mCommonCart.totalPrice);
        EventBus.getDefault().post(mCommonCart.event);

        tvGalleryProductNum.setText(productCartList.get(0).getNum() + "");
    }

    private void addProduct(Products products) {
        String date = "";
        if (isFromGallery) {
            date = HomeFragment.chooseDate;
        } else {
            date = NormalProductActivity.chooseDate;
        }
        ProductCart productCart = new ProductCart(null, products.getProduct().getCategoryId(), products.getProduct().getId(), date);
        List<ProductCart> productCartList = getProductList(products.getProduct().getCategoryId(), products.getProduct().getId(), date);

        if (productCartList.size() == 0) {
            productCart.setNum(1);
            productCart.setImage(imageIndexStr + products.getProduct().getImage());
            productCart.setName(products.getProduct().getName());
            productCart.setProductClassId(products.getProduct().getProductClassId());
            productCart.setPrice(products.getProduct().getPrice());
            productCart.setTotalPrice(products.getProduct().getPrice());
            productCart.setProductId(products.getProduct().getId());
            mProductCartDao.insert(productCart);
            tvGalleryProductNum.setText(productCart.getNum() + "");
        } else {
            productCartList.get(0).setNum(productCartList.get(0).getNum() + 1);
            productCartList.get(0).setTotalPrice(productCartList.get(0).getPrice() * productCartList.get(0).getNum());
            mProductCartDao.update(productCartList.get(0));
            tvGalleryProductNum.setText(productCartList.get(0).getNum() + "");
        }
        mCommonCart.totalNum += 1;
        mCommonCart.totalPrice += products.getProduct().getPrice();
        mCommonCart.event.setTotalNum(mCommonCart.totalNum);
        mCommonCart.event.setTotalPrice(mCommonCart.totalPrice);
        EventBus.getDefault().post(mCommonCart.event);
    }

    public List<ProductCart> getProductList(int categoryId, int productId, String chooseDate) {
        qb = mProductCartDao.queryBuilder();
        ProductCart productCart = new ProductCart(null, categoryId, productId, chooseDate);
        Query query = qb.where(
                ProductCartDao.Properties.Date.eq(productCart.getDate()), ProductCartDao.Properties.ProductId.eq(productCart.getProductId()))
                .build();
        return query.list();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(CartEvent event) {
//        tvGalleryProductNum.setText(event.getTotalNum()+"");
    }


    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.alpha_in, R.anim.alpha_out);
    }

    @Override
    protected void destroyView() {
        super.destroyView();
        EventBus.getDefault().unregister(this);
    }

}
